#include "ImgMorphology.h"

ImgMorphology::ImgMorphology(QImage *m_Img1)
{
    m_Img = m_Img1;
    m_ImgOriginal = m_Img1;
}

QImage* ImgMorphology::toErosion()
{
    QImage *newImg = new QImage(m_Img->width(), m_Img->height(), QImage::Format_ARGB32);
    for(int y = 0; y<m_Img->height(); y++)
    {
        QRgb * line = (QRgb *)m_Img->scanLine(y);
        for(int x = 0; x<m_Img->width(); x++)
        {
            vector<int> minPixel = getMaxPixel(x,y);
            newImg->setPixel(x,y, qRgb(minPixel[0], minPixel[1], minPixel[2]));
        }
    }
    return newImg;

}
QImage* ImgMorphology::toExpansion()
{
    QImage *newImg = new QImage(m_Img->width(), m_Img->height(), QImage::Format_ARGB32);
    for(int y = 0; y<m_Img->height(); y++)
    {
        QRgb * line = (QRgb *)m_Img->scanLine(y);
        for(int x = 0; x<m_Img->width(); x++)
        {
            vector<int> maxPixel = getMinPixel(x,y);
            newImg->setPixel(x,y, qRgb(maxPixel[0], maxPixel[1], maxPixel[2]));
        }
    }
    return newImg;
}

QImage* ImgMorphology::toOpening()
{
    QImage *newImg = new QImage(m_Img->width(), m_Img->height(), QImage::Format_ARGB32);
    return newImg;

}

QImage* ImgMorphology::toClosing()
{
    QImage *newImg = new QImage(m_Img->width(), m_Img->height(), QImage::Format_ARGB32);
    return newImg;

}

vector<int> ImgMorphology::getMaxPixel(int x, int y)
{
    vector<int> res = {0, 0, 0};
    vector<vector<int>> neighborhood = {{0,-1},{0,1},{-1,0},{1,0},{-1,-1},{-1,1},{1,-1},{1,1}};

    for (int i = 0; i<8; i++) {
        int thisX = x + neighborhood[i][0];
        int thisY = y + neighborhood[i][1];

        vector<int> thisAvg = getPixelAvg(thisX, thisY);
        if((thisAvg[0] != -1.0))
        {
            if(thisAvg[0] > res[0]) res[0] = thisAvg[0];
            if(thisAvg[1] > res[1]) res[1] = thisAvg[1];
            if(thisAvg[2] > res[2]) res[2] = thisAvg[2];
        }
    }
    return res;
}
vector<int> ImgMorphology::getMinPixel(int x, int y)
{
    vector<int> res = {256, 256, 256};
    vector<vector<int>> neighborhood = {{0,-1},{0,1},{-1,0},{1,0},{-1,-1},{-1,1},{1,-1},{1,1}};

    for (int i = 0; i<8; i++) {
        int thisX = x + neighborhood[i][0];
        int thisY = y + neighborhood[i][1];

        vector<int> thisAvg = getPixelAvg(thisX, thisY);
        if((thisAvg[0] != -1.0))
        {
            if(thisAvg[0] < res[0]) res[0] = thisAvg[0];
            if(thisAvg[1] < res[1]) res[1] = thisAvg[1];
            if(thisAvg[2] < res[2]) res[2] = thisAvg[2];
        }
    }
    return res;
}

vector<int> ImgMorphology::getPixelAvg(int x, int y){
    if((x<0)||(x>m_Img->width()-1)||(y<0)||(y>m_Img->height()-1)){ return {-1,-1,-1};}
    QRgb pix = m_Img->pixel(x, y);
    return {qRed(pix), qGreen(pix), qBlue(pix)};
}
